var defects = [];
var currentDefects = [];
var table;
var undefinedReplace = '空';
var start = $('#startTime').val();
var end = $('#endTime').val();
var stationId = $('#stationId').val();
var columns = [localeTitle.XuHao, localeTitle.DiaoGuanFanWei, localeTitle.ChangZhanMingCheng, localeTitle.SheBei,
		localeTitle.BaoHuXingHao, localeTitle.BaoHuTuiChuShiJian, localeTitle.BaoHuTouRuShiJian,
		localeTitle.QueXianMiaoShu, localeTitle.JianChaJiChuLiQingKuang ];
var initColumns = columns;
var stationsLength = 0;
function init() {
	$('#start').val($('#startTime').val());
	$('#end').val($('#endTime').val());
	$('#stationId').val($('#stationId').val());
	$('#start').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	$('#end').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		pickerPosition : 'bottom-left',
		todayHighlight : true
	});
	loadColumnsFilter(initColumns);
	loadData();
}
function loadData() {
	$.getJSON("/rest/protectDefect/getProtectDefect/" + start + "/" + end, function(result) {
		defects = result;
		if (stationId == "" || stationId == null || typeof (stationId) == "undefined") {
			loadFilter(stationId);
		} else {
			$('#selectButton').hide();
		}
		currentDefects = [];
		if (stationId) {
			for ( var i in defects) {
				if (defects[i].substationId == stationId) {
					currentDefects.push(defects[i]);
				}
			}
			loadContent(currentDefects);
		} else {
			currentDefects = defects;
			loadContent(defects);
		}

	});
}
function loadDataByStationId() {
	$.getJSON("/rest/protectDefect/getProtectDefectByStationId/" + start + "/" + end + "/" + stationId,
			function(result) {
				defects = result;
				$('#selectButton').hide();
				currentDefects = [];
				for ( var i in defects) {
					if (defects[i].substationId == stationId) {
						currentDefects.push(defects[i]);
					}
				}
				loadContent(currentDefects);
			});
}
function query() {
	var s = $('#start').val();
	var e = $('#end').val();
	if (stationId != "" && stationId != null && typeof (stationId) != "undefined") {
		start = s;
		end = e;
		loadDataByStationId();
	} else {
		if (s == start && e == end) {
			doFilter();
		} else {
			start = s;
			end = e;
			loadData();
		}
	}
}
function loadFilter() {
	var stations = [];
	var stationMap = {};
	for ( var i in defects) {
		var a = defects[i];
		var station = a.substationName ? a.substationName : undefinedReplace;
		if (stations.indexOf(station) == -1) {
			stations.push(station);
		}
		// 加title
		var s = stationMap[station];
		if (!s) {
			s = {
				count : 0
			};
			stationMap[station] = s;
		}
		s.count++;
	}
	// 先按照count排，count相同按照总时长
	stations.sort(sortStations);
	stationsLength = stations.length;
	$('#stations').html(getCheckBox(stations, 'stations', 'doFilter();', stationMap, stations));
	function sortStations(station1, station2) {
		var t1 = station1 == undefinedReplace ? 0 : 1;
		var t2 = station2 == undefinedReplace ? 0 : 1;
		if (t2 + t1 < 2) {
			return t2 - t1;
		}
		var m1 = stationMap[station1];
		var m2 = stationMap[station2];
		return m2.count - m1.count;
	}
}
function loadColumnsFilter(selectColumns) {
	if (!selectColumns) {
		selectColumns = columns;
	}
	$('#columns').html(getCheckBox(columns, 'columns', 'doColumnFilter();', null, selectColumns));
}
function doFilter() {
	var stations = getCheckBoxValue('stations');
	changeSelectButtonStatus(stations);
	currentDefects = [];
	for ( var i in defects) {
		var a = defects[i];
		var station = a.substationName ? a.substationName : undefinedReplace;
		if (stations.indexOf(station) > -1) {
			currentDefects.push(a);
		}
	}
	loadContent(currentDefects);
}
function changeSelectButtonStatus(stations) {
	if (stations.length == stationsLength) {
		$('#selectButton').removeClass('hasSelected');
	} else {
		$('#selectButton').addClass('hasSelected');
	}
}
function changeColumnsSelectButtonStatus(length) {
	if (columns.length == length) {
		$('#columnsSelectButton').removeClass('hasSelected');
	} else {
		$('#columnsSelectButton').addClass('hasSelected');
	}
}
function getCheckBoxValue(name) {
	var obj = document.getElementsByName(name);
	var s = [];
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			s.push(obj[i].value);
		}
	}
	return s;
}
function getCheckBox(data, name, func, map, selects) {
	var c = '';
	for ( var i in data) {
		if (map) {
			var item = map[data[i]];
			var count = item.count;
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label title="' + localeTitle.GongJi + count + localeTitle.Tiao + '"><input name="' + name
					+ '" type="checkbox" onchange="' + func + '" ' + checked + ' value="' + data[i] + '" />' + data[i]
					+ '</label>';
		} else {
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label><input name="' + name + '" type="checkbox" onchange="' + func + '" ' + checked + ' value="'
					+ data[i] + '" />' + data[i] + '</label>';
		}

	}
	return c;
}
function loadContent(defects) {
	loadTable(defects);
	refreshAllSelectAllButtonStatus();
}
function loadTable(defects) {
	if (table) {
		table.getTable().destroy();
	}
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = false;
	var defs = [ {
		"width" : "3%",
		"targets" : 0
	},// width为列宽，单位px或%均可；targets表示设置哪一列
	{
		"width" : "5%",
		"targets" : 1
	}, {
		"width" : "5%",
		"targets" : 2
	}, {
		"width" : "10%",
		"targets" : 3
	}, {
		"width" : "5%",
		"targets" : 4
	}, {
		"width" : "10%",
		"targets" : 5
	}, {
		"width" : "10%",
		"targets" : 6
	} ];
	opt.scrollY = scrollYHeight +"px";
	opt.scrollX = false;
	var datas = [];
	for ( var i in defects) {
		var f = defects[i];
		datas.push([ Number(i) + 1, str(f['subControlArea']), str(f['substationName']), str(f['name']),
				str(f['protectType']), time(f['protectInTime']), time(f['protectQuitTime']),
				str(f['defectDescription']), str(f['linePatrolReasult']) ]);
	}
	// 筛选列
	var eles = document.getElementsByName('columns');
	var targets = [];
	for (var i = 0; i < eles.length; i++) {
		if (!eles[i].checked) {
			targets.push(i);
		}
	}
	defs.push({
		visible : false,
		targets : targets
	});
	opt.columnDefs = defs;
	table = new MyTable("defectTable", columns, opt);
	table.setDataSet(datas).show();
}
function minusTime(t1, t2) {
	var d1 = new Date(t1.time ? t1.time : t1);
	var d2 = new Date(t2.time ? t2.time : t2);
	return ((d1.getTime() - d2.getTime()) / 60000).toFixed(2);
}
function selectAll(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doFilter();
}
function selectAllColumns(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doColumnFilter();
}
function doColumnFilter() {
	var eles = document.getElementsByName("columns");
	var length = 0;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		var col = table.getTable().column(i);
		col.visible(show);
		if (show) {
			length++;
		}
	}
	changeColumnsSelectButtonStatus(length);
	redrawTable();
}
function redrawTable() {
	if (table) {
		table.getTable().draw();
	}
	// $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
}
function str(v) {
	return v ? v : '';
}
function time(v) {
	if (!v) {
		return '';
	} else {
		return new Date(v.time ? v.time : v).toLocaleString();
	}
}
function refreshAllSelectAllButtonStatus() {
	var ids = [ 'columns', 'stations' ];
	for ( var i in ids) {
		refreshSelectAllButtonStatus(ids[i]);
	}
}
function refreshSelectAllButtonStatus(id) {
	var eles = document.getElementsByName(id);
	var all = document.getElementById(id + 'All');
	var checked = true;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		if (!show) {//
			checked = false;
			break;
		}
	}
	all.checked = checked;
}

function resizeHtml() {
	if (table) {
		table.getTable().draw();
	}
}